package vipers

import (
	"context"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/asserts"
	"gitee.com/lailonghui/vehicle-supervision-framework/pkg/loggers"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

func InitEtcdRemote() {
	viper.RemoteConfig = &EtcdRemoteConfig{}
}

// 使用etcd进行配置
func ConfigWithEtcd(valueInit, onValueChange func(v *viper.Viper), endpoint, path string) {

	v := viper.New()

	// 从配置中心取值
	loggers.Info("获取配置文件", context.Background(), zap.String("endpoint", endpoint), zap.String("path", path))
	err := v.AddRemoteProvider("etcd", endpoint, path)
	asserts.Nil(err, err)
	v.SetConfigType("yaml")
	// 初始化
	go func() {
		err = v.ReadRemoteConfig()
		asserts.Nil(err, err)
		valueInit(v)
		asserts.Nil(err, err)
		for true {
			err := v.WatchRemoteConfig()
			if err != nil {
				loggers.Error("监听etcd配置异常", context.Background(), zap.String("endpoint", endpoint), zap.String("path", path), zap.Error(err))
			} else {
				onValueChange(v)
			}
		}
	}()

}
